package com.xiaokai.cotroller;


import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaokai.model.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.TreeMap;

@Slf4j
@RestController()
public class OrderController {

    private static final OkHttpClient client = new OkHttpClient();

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Autowired
    private MiddlewareProperties middlewareProperties;


    @PostMapping("status/callback")
    public ResponseEntity<String> callback(@org.springframework.web.bind.annotation.RequestBody BaseDTO baseDTO) {
        log.info("data: {}", JSONObject.toJSONString(baseDTO));
        return ResponseEntity.ok("{\"status\":\"200\", \"msg\":\"接收成功\", \"data\":\"\"}");
    }

    @GetMapping("create")
    public String creat() throws IOException {
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("多彩科创园楼顶")
                .toAddress("多彩科创园地面平地")
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }

    @GetMapping("create2")
    public String creat2() throws IOException {
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(19))
                .fromAddress("多彩DOCK")
                .toAddress("多彩DOCK")
                .build();
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId("1111")
                .sign("1111")
                .timestamp("1111")
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }


    @GetMapping("create3")
    public String creat3() throws IOException {
        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        OrderDTO.Good good1 = new OrderDTO.Good("炒面", 2, 50);
        OrderDTO.Good good2 = new OrderDTO.Good("火锅", 1, 100);
        goods.add(good1);
        goods.add(good2);
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("白泉文化公园")
                .toAddress("管委会大楼南门前广场")
                .goods(goods)
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }

    @GetMapping("create4")
    public String creat4() throws IOException {
        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        OrderDTO.Good good1 = new OrderDTO.Good("炒面", 2, 50);
        OrderDTO.Good good2 = new OrderDTO.Good("火锅", 1, 100);
        goods.add(good1);
        goods.add(good2);
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("中大型起降位L1")
                .toAddress("中大型起降位M2")
                .goods(goods)
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }

    // 舟山航线测试
    @GetMapping("create5")
    public String creat5() throws IOException {
        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        OrderDTO.Good good1 = new OrderDTO.Good("炒面", 2, 50);
        OrderDTO.Good good2 = new OrderDTO.Good("火锅", 1, 100);
        goods.add(good1);
        goods.add(good2);
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("白泉文化公园")
                .fromLongitude(122.160752)
                .fromLatitude(30.06437)
                .toAddress("管委会大楼北侧广场")
                .toLongitude(122.21186729)
                .toLatitude(30.09532109)
                .goods(goods)
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }

    @GetMapping("create6")
    public String creat6() throws IOException {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderNo(RandomStringUtils.randomNumeric(12));
        orderDTO.setFromAddress("民治dock起降场L");
        orderDTO.setFromLongitude(114.0600127);
        orderDTO.setFromLatitude(22.69060644);
        orderDTO.setToAddress("民治dock起降场M");
        orderDTO.setToLongitude(114.0600127);
        orderDTO.setToLatitude(22.69060644);
        orderDTO.setAdCode("310106");
        orderDTO.setEosId("1234567890");
        orderDTO.setFromId("123456789011111");
        orderDTO.setFromMobile("13811111111");
        orderDTO.setFromSenderName("无人机集取点");
        orderDTO.setRemarks("依据餐量提供");
        orderDTO.setRequireReceiveTime(generateTimeTwoHoursLater());
        orderDTO.setToAddressDetail("北侧广场");
        orderDTO.setToMobile("13811111112");

        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        for (int i = 0; i < (int) (Math.random() * 5); i++) {
            OrderDTO.Good good1 = new OrderDTO.Good(getGoodsName(), getGoodsNum(), getGoodsPrice());
            goods.add(good1);
        }

        orderDTO.setGoods(goods);

        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(orderDTO));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(orderDTO))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }


    private String getGoodsName() {
        String[] goodsName = {"炒面", "火锅", "烤肉", "麻辣烫", "海鲜火锅", "烧烤", "披萨", "牛排", "羊肉", "牛肉火锅", "烤鸭", "海鲜"};
        int index = (int) (Math.random() * goodsName.length);
        return goodsName[index];
    }

    private Integer getGoodsNum() {
        return (int) (Math.random() * 10) + 1;
    }

    private Integer getGoodsPrice() {
        return (int) (Math.random() * 1000) + 1;
    }

    private String generateTimeTwoHoursLater() {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime timeTwoHoursLater = currentTime.plusHours(2);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return timeTwoHoursLater.format(formatter);
    }


    @GetMapping("create7")
    public String creat7() throws IOException {
        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        OrderDTO.Good good1 = new OrderDTO.Good("炒面", 2, 50);
        OrderDTO.Good good2 = new OrderDTO.Good("火锅", 1, 100);
        goods.add(good1);
        goods.add(good2);
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("中大型起降位L3")
                .fromLongitude(122.222295)
                .fromLatitude(30.111124)
                .toAddress("中大型起降位M4")
                .toLongitude(122.222721)
                .toLatitude(30.111964)
                .goods(goods)
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }


    /**
     * 舟山基地测试
     * @return
     * @throws IOException
     */
    @GetMapping("create8")
    public String creat8() throws IOException {
        ArrayList<OrderDTO.Good> goods = new ArrayList<>();
        OrderDTO.Good good1 = new OrderDTO.Good("炒面", 2, 50);
        OrderDTO.Good good2 = new OrderDTO.Good("火锅", 1, 100);
        goods.add(good1);
        goods.add(good2);
        OrderDTO order = OrderDTO.builder()
                .orderNo(RandomStringUtils.randomNumeric(12))
                .fromAddress("中大型起降位L1")
                .fromLongitude(122.244495)
                .fromLatitude(30.104124)
                .toAddress("中大型起降位L1")
                .toLongitude(122.244495)
                .toLatitude(30.104124)
                .goods(goods)
                .build();
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", middlewareProperties.getAppId());
        params.put("timestamp", timestamp);
        params.put("data", JSONObject.toJSONString(order));
        String sign = SignatureUtils.generateSignature(middlewareProperties.getAppSecret(), params);
        log.info("sign: {}, timestamp: {}", sign, timestamp);
        BaseDTO<Object> dto = BaseDTO.builder()
                .appId(middlewareProperties.getAppId())
                .sign(sign)
                .timestamp(timestamp)
                .data(OBJECT_MAPPER.writeValueAsString(order))
                .build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(UrlConstant.BASE_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(dto), MediaType.parse(ContentType.JSON.getValue())));
        Response response = null;
        try {
            response = client.newCall(requestBuilder.build()).execute();
        } catch (IOException e) {
            log.error("推送订单失败", e.getMessage());
        }
        ResponseBody body = response.body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(body.string());
        log.info("推单成功");
        return jsonObject.toString();
    }

}
